/**
 * 颜色处理工具类
 */
export const colorTools = {
  /**
   * 将十六进制颜色转换为RGB数组
   * @param {string} hex 十六进制颜色值
   * @returns {Array} RGB数组 [r, g, b]
   */
  hexToRgb(hex) {
    const cleanHex = hex.replace('#', '');
    return [
      parseInt(cleanHex.substr(0, 2), 16),
      parseInt(cleanHex.substr(2, 2), 16),
      parseInt(cleanHex.substr(4, 2), 16)
    ];
  },

  /**
   * 计算两个颜色之间的差异
   * @param {Array} color1 第一个颜色的RGB数组
   * @param {Array} color2 第二个颜色的RGB数组
   * @returns {number} 颜色差异值
   */
  colorDifference(color1, color2) {
    return Math.sqrt(
      (color1[0] - color2[0]) ** 2 + 
      (color1[1] - color2[1]) ** 2 + 
      (color1[2] - color2[2]) ** 2
    );
  },

  /**
   * 应用透明度处理到图像数据
   * @param {ImageData} imageData 图像数据
   * @param {Array} targetColor 目标颜色RGB数组
   * @param {number} threshold 阈值
   * @returns {ImageData} 处理后的图像数据
   */
  applyTransparency(imageData, targetColor, threshold) {
    const data = imageData.data;
    const [tr, tg, tb] = targetColor;

    for (let i = 0; i < data.length; i += 4) {
      const diff = this.colorDifference([data[i], data[i + 1], data[i + 2]], [tr, tg, tb]);
      data[i + 3] = diff < threshold ? 0 : 255;
    }

    return imageData;
  }
};